import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:sciolto/POJO/Song.dart';
import 'package:sciolto/POJO/SongList.dart';
import 'package:sciolto/api/music.dart';
import 'package:sciolto/util/setting.dart';

enum typeOfCreation { song, songlist }

class CustomWidget {
  static Widget customSongListSet(
      String listName,
      List<SongList> listOfSonglist,
      Size _size,
      BuildContext context,
      String imagePath,
      VoidCallback onPressed,
      VoidCallback onLongPressed) {
    double _x = _size.width / 420, _y = _size.height / 800;
    return Expanded(
      flex: 1,
      child: Container(
        width: _size.width,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              width: _size.width,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 20 * _x),
              child: Text(
                listName,
                style: TextStyle(
                    fontSize: 15 * _x,
                    color: Colors.black,
                    wordSpacing: 1,
                    fontWeight: FontWeight.w900),
              ),
            ),
            Container(
              height: 5 * _y,
            ),
            Expanded(
              flex: 1,
              child: LayoutBuilder(
                builder: (context, constraints) {
                  return Container(
                    child: ListView.separated(
                        physics: BouncingScrollPhysics(),
                        scrollDirection: Axis.horizontal,
                        itemBuilder: (BuildContext context, index) {
                          SongList currentSonglist = listOfSonglist[index];
                          return Padding(
                            padding: EdgeInsets.all(20 * _x),
                            child: Ink(
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(10 * _y)),
                              child: InkWell(
                                borderRadius: BorderRadius.circular(10 * _y),
                                child: MaterialButton(
                                  onPressed: onPressed,
                                  onLongPress: onLongPressed,
                                  padding: EdgeInsets.all(0),
                                  shape: RoundedRectangleBorder(
                                      borderRadius:
                                          BorderRadius.circular(10 * _y)),
                                  elevation: 8,
                                  highlightElevation: 2,
                                  minWidth: 140 * _x,
                                  height: constraints.maxHeight,
                                  color: Setting.songListButtonFrontColor,
                                  child: Container(
                                    width: 140 * _x,
                                    decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.circular(10 * _y),
                                    ),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Expanded(
                                            flex: 5,
                                            child: Container(
                                              width: 180 * _x,
                                              // TODO: 需更新为具体图片
                                              child: ClipRRect(
                                                borderRadius: BorderRadius.only(
                                                    topLeft: Radius.circular(
                                                        10 * _y),
                                                    topRight: Radius.circular(
                                                        10 * _y)),
                                                child: Image(
                                                  alignment:
                                                      Alignment.topCenter,
                                                  fit: BoxFit.cover,
                                                  image: AssetImage(
                                                      currentSonglist
                                                          .imagePath),
                                                ),
                                              ),
                                              decoration: BoxDecoration(
                                                borderRadius: BorderRadius.only(
                                                    topLeft: Radius.circular(
                                                        10 * _y),
                                                    topRight: Radius.circular(
                                                        10 * _y)),
                                              ),
                                            )),
                                        Expanded(
                                            flex: 2,
                                            child: Container(
                                              width: 180 * _x,
                                              padding: EdgeInsets.fromLTRB(
                                                  10 * _x, 10 * _y, 10 * _x, 0),
                                              decoration: BoxDecoration(
                                                borderRadius: BorderRadius.only(
                                                    bottomLeft: Radius.circular(
                                                        10 * _y),
                                                    bottomRight:
                                                        Radius.circular(
                                                            10 * _y)),
                                              ),
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Expanded(
                                                      flex: 2,
                                                      child: Padding(
                                                        padding: EdgeInsets
                                                            .symmetric(
                                                                horizontal:
                                                                    5 * _x),
                                                        child: Text(
                                                          currentSonglist
                                                              .listName,
                                                          style: TextStyle(
                                                              color: Colors
                                                                  .cyan[300]),
                                                          overflow: TextOverflow
                                                              .ellipsis,
                                                          maxLines: 1,
                                                        ),
                                                      )),
                                                  Expanded(
                                                      flex: 2,
                                                      child: Container(
                                                        child: Row(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .center,
                                                          children: [
                                                            Image(
                                                                image: AssetImage(
                                                                    "images/arrow_right_filling.png")),
                                                            Container(
                                                              width: 5 * _x,
                                                            ),
                                                            Text(
                                                              "${currentSonglist.hits} ${currentSonglist.hits < 1 ? "click" : "clicks"}",
                                                              style: TextStyle(
                                                                  color: Colors
                                                                          .grey[
                                                                      300]),
                                                            )
                                                          ],
                                                        ),
                                                        padding:
                                                            EdgeInsets.only(
                                                                bottom: 5 * _y),
                                                      )),
                                                ],
                                              ),
                                            ))
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          );
                        },
                        separatorBuilder: (context, index) {
                          return Container(
                            width: 20 * _x,
                          );
                        },
                        itemCount: listOfSonglist.length),
                  );
                },
              ),
            )
          ],
        ),
      ),
    );
  }

  static Widget customBackButton(
      width, height, BuildContext context, Color color) {
    return SizedBox(
      width: width,
      height: height,
      child: IconButton(
        icon: Image(
          image: AssetImage("images/back.png"),
          color: color,
        ),
        onPressed: () {
          Navigator.of(context).pop();
        },
        padding: EdgeInsets.all(0),
      ),
    );
  }

  // static Widget customSongList(List<Map<String, String>> songList, _x, _y, width, height, BuildContext context){
  //   return Container(
  //     width: width,
  //     height: height + 1.0,
  //     padding: EdgeInsets.symmetric(vertical: 20 * _y),
  //     child: ListView.builder(
  //         physics: BouncingScrollPhysics(),
  //         itemCount: songList.length,
  //         itemBuilder: (context, index){
  //           return Container(
  //             width: width,
  //             height: 50 * _y,
  //             padding: EdgeInsets.symmetric(horizontal: 20 * _x),
  //             child: Column(
  //               children: [
  //                 Expanded(
  //                   flex: 1,
  //                   child: Container(
  //                     alignment: Alignment.centerLeft,
  //                     child: Text(
  //                       songList[index]['songName'],
  //                       style: TextStyle(
  //                         fontSize: 20 * _x,
  //                       ),
  //                     ),
  //                   ),
  //                 ),
  //                 Expanded(
  //                   flex: 1,
  //                   child: Container(
  //                     alignment: Alignment.centerLeft,
  //                     child: Text(
  //                       songList[index]['singer'],
  //                       style: TextStyle(
  //                         fontSize: 20 * _x,
  //                       ),
  //                     ),
  //                   ),
  //                 )
  //               ],
  //             ),
  //           );
  //         }
  //     ),
  //   );
  // }

  /// 播放列表
  static void showPlayList(
      BuildContext context, Size _size, double _x, double _y) {
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return StatefulBuilder(
            builder: (context1, setBottomSheetState) {
              List<Song> listOfSong = PlayList().listOfSong;
              String path, stateName;
              switch (PlayList().currentType) {
                case PlayerType.common:
                  path = Setting.playListStateCommon;
                  stateName = "普通模式";
                  break;
                case PlayerType.singleCycle:
                  path = Setting.playListStateSingleCycle;
                  stateName = "单曲循环";
                  break;
                case PlayerType.listCycle:
                  path = Setting.playListStateListCycle;
                  stateName = "列表循环";
                  break;
                case PlayerType.random:
                  path = Setting.playListStateRandom;
                  stateName = "随机播放";
                  break;
              }
              return Padding(
                padding: EdgeInsets.all(20 * _y),
                child: Container(
                    width: _size.width,
                    height: _size.height / 2,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(30 * _y),
                        color: Colors.grey[50]),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                            height: 40 * _y,
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.symmetric(
                                horizontal: 20 * _y, vertical: 5 * _y),
                            child: GestureDetector(
                              onTap: () {
                                setBottomSheetState(() {
                                  PlayList().currentType = PlayerType.values[
                                      (PlayList().currentType.index + 1) %
                                          PlayerType.values.length];
                                });
                              },
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Image(
                                    color: Setting.itemHighLight,
                                    width: 30 * _y,
                                    height: 30 * _y,
                                    image: AssetImage(path),
                                  ),
                                  SizedBox(
                                    width: 10 * _x,
                                  ),
                                  Text(
                                    stateName,
                                    style: TextStyle(
                                        fontSize: 10 * _y,
                                        color: Setting.itemHighLight),
                                  )
                                ],
                              ),
                            )),
                        Expanded(
                          child: ReorderableListView(
                            shrinkWrap: true,
                            children: [
                              for (int index = 0;
                                  index < listOfSong.length;
                                  index++)
                                GestureDetector(
                                  key: ValueKey(listOfSong[index]),
                                  onTap: () {
                                    PlayList().selectMusic(
                                        index, PlayList().currentSongList);
                                    setBottomSheetState(() {});
                                  },
                                  child: Container(
                                    color: Colors.grey[50],
                                    width: _size.width,
                                    alignment: Alignment.centerLeft,
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 20 * _y),
                                    child: Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Container(
                                          width: 200 * _x,
                                          padding: EdgeInsets.symmetric(
                                              vertical: 10 * _y),
                                          child: Text(
                                            listOfSong[index].songName,
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 1,
                                            style: TextStyle(
                                                fontSize: 12 * _y,
                                                color: index ==
                                                        PlayList()
                                                            .currentSongIndex
                                                    ? Colors.cyanAccent
                                                    : Colors.grey),
                                          ),
                                        ),
                                        Spacer(
                                          flex: 1,
                                        ),
                                        SizedBox(
                                          child: IconButton(
                                              icon: Icon(
                                                Icons.close,
                                                color: Setting.itemHighLight,
                                              ),
                                              onPressed: () {
                                                PlayList()
                                                    .deleteSongFromListWithIndex(
                                                        index);
                                              }),
                                        )
                                      ],
                                    ),
                                  ),
                                )
                            ],
                            onReorder: (oldIndex, newIndex) {
                              PlayList().moveMusic(oldIndex, newIndex);
                              setBottomSheetState(() {});
                            },
                          ),
                        ),
                        SizedBox(
                          height: 40 * _y,
                        )
                      ],
                    )),
              );
            },
          );
        });
  }

  static Future<T> showCustomDialog<T>({
    @required BuildContext context,
    bool barrierDismissible = true,
    WidgetBuilder builder,
  }) {
    return showGeneralDialog(
      context: context,
      pageBuilder: (BuildContext buildContext, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        final Widget pageChild = Builder(builder: builder);
        return SafeArea(
          child: Builder(builder: (BuildContext context) {
            return pageChild;
          }),
        );
      },
      barrierDismissible: barrierDismissible,
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
      transitionDuration: const Duration(milliseconds: 150),
      transitionBuilder: _buildMaterialDialogTransitions,
    );
  }

  static Widget _buildMaterialDialogTransitions(
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child) {
    // 使用缩放动画
    return ScaleTransition(
      scale: CurvedAnimation(
        parent: animation,
        curve: Curves.easeOut,
      ),
      child: child,
    );
  }

  static Future<T> showCreateSonglistView<T>(
      BuildContext context, Size size, double x, double y) {
    TextEditingController controller = TextEditingController();
    FocusNode textFocusNode = FocusNode();
    return showCustomDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                FocusScope.of(context).requestFocus(FocusNode());
              },
              child: Material(
                color: Colors.transparent,
                type: MaterialType.transparency,
                child: Padding(
                  padding: EdgeInsets.symmetric(
                    horizontal: 50 * x,
                    vertical: 290 * y,
                  ),
                  child: Card(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10 * y)
                    ),
                    shadowColor: Colors.blueGrey,
                    color: Colors.white,
                    elevation: 5,
                    child: Column(
                      children: [
                        Padding(
                          padding:
                              EdgeInsets.fromLTRB(20 * y, 20 * y, 20 * y, 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                "创建歌单",
                                style: TextStyle(
                                    fontSize: 20 * y, color: Colors.blueGrey),
                              ),
                            ],
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(
                              vertical: 20 * y, horizontal: 20 * y),
                          child: Container(
                            width: 300 * x,
                            height: 30 * y,
                            child: TextField(
                              controller: controller,
                              textAlignVertical: TextAlignVertical.center,
                              decoration: InputDecoration(
                                  hintText: "请输入歌单名称",
                                  hintStyle: TextStyle(color: Colors.grey[300]),
                                  border: OutlineInputBorder(
                                      borderRadius:
                                          BorderRadius.circular(10 * x),
                                      borderSide:
                                          BorderSide(color: Colors.cyan)),
                                  contentPadding: EdgeInsets.symmetric(
                                      vertical: 5 * y, horizontal: 10 * y)),
                              textInputAction: TextInputAction.done,
                              style: TextStyle(color: Colors.grey),
                              focusNode: textFocusNode,
                              cursorColor: Colors.blueGrey,
                              onEditingComplete: () {
                                textFocusNode.unfocus();
                              },
                            ),
                          ),
                        ),
                        Spacer(
                          flex: 1,
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Expanded(
                              flex: 1,
                              child: GestureDetector(
                                  onTap: () {
                                    textFocusNode.unfocus();
                                    Navigator.of(context).pop();
                                  },
                                  child: Container(
                                    height: 50 * y,
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.only(
                                            bottomLeft:
                                                Radius.circular(10 * y)),
                                        border: Border.all(color: Colors.blueGrey)),
                                    child: Text(
                                      "取消",
                                      style: TextStyle(
                                          fontSize: 20 * y, color: Colors.blueGrey),
                                    ),
                                  )),
                            ),
                            Expanded(
                              flex: 1,
                              child: GestureDetector(
                                  onTap: () {
                                    if (controller.text.isNotEmpty) {
                                      SongList newList = SongList(
                                          controller.text,
                                          "images/list_${controller.text.length % 7}.jpg",
                                          ImageResourceType.ASSET,
                                          "简介还没有上班，因为简介是自由的:)");
                                      SongsInfo()
                                          .createNewSongList(newList)
                                          .then((value) {
                                        switch (value) {
                                          case CreateSonglistState.duplication:
                                            showToast("创建失败: 歌单名已存在");
                                            break;
                                          case CreateSonglistState.success:
                                            showToast("创建成功");
                                            Navigator.of(context).pop();
                                            break;
                                          case CreateSonglistState.error:
                                            showToast("创建失败: 出现预料之外的错误");
                                            break;
                                        }
                                      });
                                    } else {
                                      showToast("歌单名不能为空哦");
                                    }
                                  },
                                  child: Container(
                                    height: 50 * y,
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.only(
                                            bottomRight:
                                                Radius.circular(10 * y)),
                                        border: Border.all(color: Colors.blueGrey)),
                                    child: Text(
                                      "创建",
                                      style: TextStyle(
                                          fontSize: 20 * y, color: Colors.blueGrey),
                                    ),
                                  )),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                ),
              ));
        });
  }

  static Future<T> showAlertDialog<T>(
      {@required BuildContext context,
      @required Size size,
      @required double x,
      @required double y,
      @required String title,
      @required String content,
      @required VoidCallback onPressConfirm,
      SongList songlist}) {
    return showCustomDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return Padding(
            padding: EdgeInsets.symmetric(
              horizontal: 50 * x,
              vertical: 290 * y,
            ),
            child: Card(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10 * y)
              ),
              shadowColor: Colors.blueGrey,
              color: Colors.white,
              elevation: 5,
              child: Column(
                children: [
                  Padding(
                    padding: EdgeInsets.fromLTRB(20 * y, 20 * y, 20 * y, 0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          title,
                          style: TextStyle(
                              fontSize: 20 * y,
                              color: Colors.blueGrey,
                              fontWeight: FontWeight.w900,
                              decoration: TextDecoration.none),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(
                        vertical: 20 * y, horizontal: 20 * y),
                    child: Container(
                        width: 300 * x,
                        height: 30 * y,
                        child: Text(
                          content,
                          style: TextStyle(
                              fontSize: 18 * y,
                              color: Colors.blueGrey,
                              decoration: TextDecoration.none),
                        )),
                  ),
                  Spacer(
                    flex: 1,
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        flex: 1,
                        child: GestureDetector(
                            onTap: () {
                              Navigator.of(context).pop();
                            },
                            child: Container(
                              height: 50 * y,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.only(
                                      bottomLeft: Radius.circular(10 * y)),
                                  border: Border.all(color: Colors.blueGrey)),
                              child: Text(
                                "取消",
                                style: TextStyle(
                                    fontSize: 20 * y,
                                    color: Colors.blueGrey,
                                    decoration: TextDecoration.none),
                              ),
                            )),
                      ),
                      Expanded(
                        flex: 1,
                        child: GestureDetector(
                            onTap: onPressConfirm,
                            child: Container(
                              height: 50 * y,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.only(
                                      bottomRight: Radius.circular(10 * y)),
                                  border: Border.all(color: Colors.blueGrey)),
                              child: Text(
                                "确定",
                                style: TextStyle(
                                    fontSize: 20 * y,
                                    color: Colors.blueGrey,
                                    decoration: TextDecoration.none),
                              ),
                            )),
                      ),
                    ],
                  )
                ],
              ),
            ),
          );
        });
  }

  static void showToast(
    String text, {
    gravity: ToastGravity.CENTER,
    toastLength: Toast.LENGTH_SHORT,
  }) {
    Fluttertoast.showToast(
      msg: text,
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
      backgroundColor: Colors.grey[600],
      // 灰色背景
      fontSize: 16.0,
    );
  }
}
